<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Detail extends Controller {

	public function action_index()
	{
		try {
			if ($this->request->method() == "POST"){
				// 发表评论
				$data = $this->request->post();
				$data['uid'] = 0;
				$data['ip'] = Request::$client_ip;
				$data['type'] = 3;
				$Mcomment = Model::factory('Comment');
				$cid = $Mcomment->add($data);
				if (is_numeric($cid)){
					// 累计评论数
					$Marticle = Model::factory('Article');
					$Marticle->plus_one(array('comment'), $data['aid']);
					
					header('location:' . Request::detect_uri());
					exit;
				}
			}
			
			$aid = 1;
			$param = $this->request->param('stuff');
			if (!empty($param)){
				$param_arr = explode('/', $param);
				$aid = $param_arr[0];
				$preview = isset($param_arr[1]) ? $param_arr[1] : '';
				//$comment_page = isset($param_arr[1]) ? $param_arr[1] : 1;
			}else {
				throw new Exception('参数错误');
			}
			if (!is_numeric($aid)){
				throw new Exception('参数错误');
			}
			
			$Marticle = Model::factory('Article');
			$Session = Session::instance()->as_array();
			if (isset($Session['admin_username']) && isset($preview) && $preview == 'preview'){
				$cond = array();
			}else {
				$cond = array('status' => 0);
			}
			
			$article = $Marticle->get_by_aid($aid, $cond);
			if ($article){
				$view = View::factory('detail');
				$page_title = $article['title'] . ' - ' . Function_23dian::page_title();
				$view->bind('page_title', $page_title);
				$view->bind('article', $article);
				$Marticle->plus_one(array('`read`'), $aid);
			}else {
				throw new Exception('没找到');
			}
			
			$Mcomment = Model::factory('Comment');
			//$comments = $Mcomment->get_page_by_aid($aid, $comment_page);
			$total = $Mcomment->get_count_by_aid($aid);
			$pagination = Kohana::$config->load('pagination')->get('comment');
			$pagination['total_items'] = $total;
			$pager = Pagination::factory($pagination);
			$comments['comments'] = $Mcomment->get_by_aid($aid, $pager->offset, $pager->items_per_page);
			$comments['pager'] = $pager->render();
			$view->bind('comments', $comments);
			
			$right = Include_Right::right_content();
			$view->bind('right', $right);
			
		}catch (Exception $e) {
			Kohana_Exception::log($e);
			$err_msg = Kohana_Exception::text($e);
			$view = View::factory('errors/error')
					->bind('err_msg', $err_msg);
		}
		
		$this->response->body($view);
	}

}
